package com.JWH_TV.adapters

import android.graphics.Color
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.JWH_TV.R
import com.JWH_TV.domain.Program


class ProgramAdapter(
    private val programList: List<Program>,
    private val onItemClick: (Program) -> Unit
) : RecyclerView.Adapter<ProgramAdapter.ProgramViewHolder>() {

    private var focusedPosition: Int = -1

    // ViewHolder 类
    class ProgramViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvProgramName: TextView = itemView.findViewById(R.id.tv_program_name)

        fun bind(program: Program, position: Int, onItemClick: (Program) -> Unit, focusedPosition: Int) {
            // 显示节目名称
            val displayText = "${program.urlId}. ${program.name}"
            tvProgramName.text = displayText

            // 处理点击事件
            itemView.setOnClickListener {
                onItemClick(program)
            }

            // 设置焦点
            itemView.isFocusable = true
            itemView.isFocusableInTouchMode = true

            // 监听焦点变化
            itemView.setOnFocusChangeListener { v, hasFocus ->
                if (hasFocus) {
                    // 如果获得焦点，改变背景颜色或文本颜色
                    v.setBackgroundColor(Color.parseColor("#0071b3"))  // 背景颜色修改为淡蓝色
                    (v.findViewById<TextView>(R.id.tv_program_name)).setTextColor(Color.YELLOW)  // 文本颜色修改为黄色
                } else {
                    // 如果失去焦点，恢复默认状态
                    v.setBackgroundColor(Color.TRANSPARENT)  // 背景颜色恢复透明
                    (v.findViewById<TextView>(R.id.tv_program_name)).setTextColor(Color.WHITE)  // 文本颜色恢复白色
                }
            }

            // 如果当前项是焦点项，保持焦点
            if (position == focusedPosition) {
                itemView.requestFocus()
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProgramViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_program, parent, false)
        return ProgramViewHolder(view)
    }

    override fun onBindViewHolder(holder: ProgramViewHolder, position: Int) {
        val program = programList[position]
        holder.bind(program, position, onItemClick, focusedPosition)
    }

    override fun getItemCount(): Int {
        return programList.size
    }

    // 设置当前焦点的位置
    fun setFocusedPosition(position: Int) {
        focusedPosition = position
        notifyDataSetChanged() // 更新视图以反映焦点变化
    }
}

